SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
 
 CREATE FUNCTION [Live].[AssetHelper]
 (
 @ExportId INT
 )
 
 RETURNS TABLE
 
 AS
 RETURN
 
SELECT  
       a.AssetIntrnlId,
	   a.ExportId,
		[tgpr].[NBSReason] AS NBSReason,
		ca.InstrName,
		ca.InstrClass, 
		ca.InstSortOrder,
    a.AssetType, tgpr.portfoliopurchase
        
FROM    FSFundModel.Reporting.Asset a
        INNER JOIN FSFundModel.Reporting.Instrument i ON a.ExportId = i.ExportId
                                                         AND a.InstrumentId = i.InstrumentId
        INNER JOIN FSFundModel.Reporting.InstrumentDefinition id ON i.InstDefId = id.InstDefId
                                                              AND a.ExportId = id.ExportId 
				INNER JOIN  [Live].[tvfGetPropReason](@ExportId) tgpr
						ON [tgpr].[AssetIntrnlId] = [a].[AssetIntrnlId]

		
		CROSS APPLY (

			SELECT --Live.GetPropReason(@ExportId, a.AssetIntrnlId) 
			
							--Live.GetInstrumentName(@ExportId, a.AssetIntrnlId) 
			CASE WHEN a.AssetType <> 'Instrument' THEN i.InstrName + ' - ' + REPLACE(a.AssetType , 'DelayedDraw', 'Delayed Draw')
						ELSE i.InstrName
						END  AS InstrName, 
			--Live.GetInstrumentClass(@ExportId, a.AssetIntrnlId)  
			CASE WHEN a.AssetType <> 'Instrument' THEN 'Unfunded Positions' 
				ELSE id.InstrClass 
				END 
						AS InstrClass,
			--live.GetInstrumentSortOrder(@ExportId, a.AssetIntrnlId) 
			CASE WHEN a.AssetType <> 'Instrument' THEN 90 + id.SortOrder 
						ELSE id.SortOrder
						END 
						AS InstSortOrder
			) ca
WHERE   a.ExportId = @ExportId
        AND a.IsActiveEndOfDay = 1 
GO
EXEC sp_addextendedproperty N'VirtualFolder', N'Live', 'SCHEMA', N'Live', 'FUNCTION', N'AssetHelper', NULL, NULL
GO
